package com.linkage.jz.bankruptcy.fragment.Vote;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.Vote.ProVoteVotersDetailNoGroupsAdapter;
import com.linkage.jz.bankruptcy.bean.Vote.ProVote;
import com.linkage.jz.bankruptcy.bean.Vote.ProVoteVotersDetail;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.BundleUtils;
import com.linkage.jz.bankruptcy.utils.LogUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 表决人详情Tab之已表决列表,已参会未表决列表和未参会列表（不分组）
 * see https://lanhuapp.com/web/#/item/project/board/detail?pid=19ffdabe-41f1-40c0-91af-37b491d5d596&project_id=19ffdabe-41f1-40c0-91af-37b491d5d596&image_id=26a11528-8dbd-48be-9c4f-6ef466ea789d
 */
public class ProVoteVotersFragment extends ProVoteBaseFragment {

    public static final String ARG_PARAM_STATUS = "arg_param_status";
    public static final String ARG_PARAM_GROUPID = "arg_param_group_id";
    private int STATUS = 1;//1-已表决  2-已参会未表决  3-未参会
    private ProVote proVote;
    private String groupId;
    private View rootView;

    private TextView proVoteTotalVoter;
    private LRecyclerView mRecyclerView;
    private RelativeLayout emptyView;
    private ProVoteVotersDetailNoGroupsAdapter mDataNoGroupAdapter;
    private LRecyclerViewAdapter mNoGroupAdapter;
    private List<ProVoteVotersDetail> mData;
    private int page = 1;
    private String userToken;

    public static ProVoteVotersFragment newInstance(int status, String groupId) {
        ProVoteVotersFragment fragment = new ProVoteVotersFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM_GROUPID, groupId);
        args.putInt(ARG_PARAM_STATUS, status);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        proVote = BundleUtils.getProVote();
        groupId = getArguments().getString(ARG_PARAM_GROUPID, "");
        STATUS = getArguments().getInt(ARG_PARAM_STATUS, 1);
        mData = new ArrayList<>();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(null == rootView) {
            rootView = inflater.inflate(R.layout.fragment_pro_vote_voters_details, container, false);
        }
        proVoteTotalVoter = rootView.findViewById(R.id.pro_vote_total_voter);

        mRecyclerView = rootView.findViewById(R.id.list);
        emptyView = rootView.findViewById(R.id.empty);
        mDataNoGroupAdapter = new ProVoteVotersDetailNoGroupsAdapter(getActivity(), STATUS, mData);
        mNoGroupAdapter = new LRecyclerViewAdapter(mDataNoGroupAdapter);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader); //设置下拉刷新Progress的样式
        mRecyclerView.setArrowImageView(com.github.jdsjlzx.R.drawable.progressbar);  //设置下拉刷新箭头
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setPullRefreshEnabled(true);
        mRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                fetchData();
            }
        });
        mRecyclerView.forceToRefresh();
        return rootView;
    }

    private void fetchData() {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }
        showLoading();
        userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        page = 1;
        getVotersWithNoGroup();
    }

    private void getVotersWithNoGroup() {
        mRecyclerView.setAdapter(mNoGroupAdapter);
        mRecyclerView.setLoadMoreEnabled(false);
        Network.getAPIService()
                .getVoteParticipants(userToken, proVote.getId(), proVote.getBankruptcyProjectId(), groupId, STATUS,proVote.getDefaultAgreed(), page, 100)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        LogUtil.e("--response--", json.toString());
                        JsonArray data = json.getAsJsonObject("data").getAsJsonObject("pageData").getAsJsonArray("list");
                        List<ProVoteVotersDetail> networkData = ProVoteVotersDetail.parse(data);
                        if(page == 1)
                        {
                            mData.clear();
                        }
                        mData.addAll(networkData);
                        mRecyclerView.refreshComplete(100);

                        String count = json.getAsJsonObject("data").get("memberCount").toString();
                        showTitle(count);
                        mNoGroupAdapter.notifyDataSetChanged();
                        if(mData.size() > 0) {
                            mRecyclerView.setVisibility(View.VISIBLE);
                            emptyView.setVisibility(View.GONE);
                        }else {
                            mRecyclerView.setVisibility(View.GONE);
                            emptyView.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    public void onCompleted() {
                        hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoading();
                    }
                });
    }

   public void showTitle(String count)
    {
        String str = "已表决";
        String num = "0";
        if(STATUS ==1)
        {
//            num =  proVote.getVote()+"";
        }
        if(STATUS ==2 )
        {
            str = "已参会未表决";
//            num =  proVote.getJoinMeeting()+"";
        }
        if(STATUS ==3 )
        {
//            num =  (proVote.get()-proVote.getJoinMeeting()-proVote.getVote())+"";
            str = "未参会";
        }
        proVoteTotalVoter.setText(str+"：" + count + "人");
    }

}
